import * as React from 'react';
import { Icon, Popconfirm, message } from 'antd';
import makeHoc from 'components/common/makeHoc';
import CONFIG from 'constants/config';

import LoadableComponent from 'components/common/LoadableComponent';
const LoadableAttachPopToSelect = LoadableComponent(() => import('pages/attachment/PopToSelect'));

import { saveLessonCover } from 'actions/lesson';

import { isLoading } from 'utils/utils';
import ACTIONS from 'constants/lesson';

/**
 * 图片编辑，根据type兼容封面，缩略图
 */
interface EditImageProps {
  dispatch: (action: any) => any;
  handleCallback: () => any;
  loadingGroup: any;
  courseId: number;
  lessonId: number;
  lessonImage: any;
  selectedItems: any[];
  type: number;
}

interface EditImageState {
  isSelectImage: boolean;
}
class EditImage extends React.Component<EditImageProps, EditImageState> {
  static defaultProps: EditImageProps = {
    dispatch: () => {},
    handleCallback: () => {},
    loadingGroup: false,
    courseId: 0,
    lessonId: 0,
    lessonImage: null,
    selectedItems: [],
    type: 0,
  };
  constructor(props: EditImageProps) {
    super(props);
    this.state = {
      isSelectImage: false,
    };
  }

  handleRemoveImage() {
    const { dispatch, lessonId, loadingGroup, type, handleCallback } = this.props;

    if (isLoading(loadingGroup, ACTIONS.SAVE_COVER)) return;

    dispatch(saveLessonCover(lessonId, 0, type)).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        message.success('删除成功');
        handleCallback();
      }
    });
  }

  handleCloseModal = () => {
    this.setState({
      isSelectImage: false,
    });
  };

  handleOpenModal = () => {
    this.setState({
      isSelectImage: true,
    });
  };

  ConfirmToDelete(props: any) {
    return (
      <Popconfirm
        okText="确定"
        cancelText="取消"
        title="你确定要删除此图片吗？"
        onConfirm={props.onRemove}>
        <Icon type="close" />
      </Popconfirm>
    );
  }

  handleSubmit = () => {
    const { dispatch, lessonId, selectedItems, type, handleCallback } = this.props;

    const image = selectedItems[0];

    dispatch(saveLessonCover(lessonId, image.id, type)).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        message.success('保存成功');

        this.handleCloseModal();
        handleCallback();
      }
    });
  };

  renderItems = (): any => {
    const { lessonImage: image } = this.props;

    if (!image) {
      return (
        <p className="loading-placeholder">
          <Icon type="frown-o" />&nbsp;还没有数据，&nbsp;
          <a href="javascript:void(0);" onClick={this.handleOpenModal}>
            <Icon type="plus" />添加
          </a>
        </p>
      );
    }

    return (
      <div
        key={image.id}
        className="classic-upload-item"
        style={{ display: 'flex', alignItems: 'center' }}>
        <div className="classic-thumbnail">
          <img src={image.uri} alt="图片" />
        </div>
        <div className="classic-item-name">{image.name}</div>
        <div className="classic-operation">
          <this.ConfirmToDelete
            onRemove={() => {
              this.handleRemoveImage();
            }}
          />
        </div>
      </div>
    );
  };

  render() {
    const { loadingGroup, lessonImage } = this.props;
    const { isSelectImage } = this.state;
    let ownItems = [];
    if (lessonImage) {
      ownItems.push(lessonImage);
    }

    return (
      <div>
        {isSelectImage && (
          <LoadableAttachPopToSelect
            loading={isLoading(loadingGroup, ACTIONS.UPDATE)}
            selectMax={1}
            selectType={CONFIG.ITEM_IMAGE}
            ownItems={ownItems}
            onCancel={this.handleCloseModal}
            onOk={this.handleSubmit}
          />
        )}
        {this.renderItems()}
      </div>
    );
  }
}

interface OwnProps {
  type: number;
  courseId: number;
  lessonId: number;
  lessonImage: any;
  handleCallback: () => any;
}

function mapStateToProps(state: any, ownProps: OwnProps) {
  const { loadingGroup } = state;
  const { selectedItems } = state.attachment;
  const { type, courseId, lessonId, lessonImage, handleCallback } = ownProps;
  return {
    type,
    courseId,
    lessonId,
    lessonImage,
    loadingGroup,
    handleCallback,
    selectedItems,
  };
}

export default makeHoc(mapStateToProps)(EditImage, {
  addImage() {
    this.handleOpenModal();
  },
});
